#pragma once
#include "socket.h"
#include "calculate.h"

using func_t = function<void(my_socket *)>; // 执行任务的方法

class tcp_server
{
public:
    tcp_server(uint16_t port, func_t f)
        : _port(port), _sv(new tcp_socket()), _func(f)
    {
        _sv->tcpserver_socket(port);
    }

    void thread_run(my_socket *socket) // 线程执行区域
    {
        _func(socket);

        socket->Close(); // 运行完毕就直接关闭accept返回的套接字描述符
    }
    
    void loop()
    {
        while (1)
        {
            string client_ip;
            uint16_t client_port;
            my_socket *socket = _sv->Accept(client_ip, client_port); // 接收套接字
            cout << "获取新连接,ip= " << client_ip << " port= " << client_port << endl;

            // sleep(3);
            // _sv->Close();//监听套接字就是用来接收多个客户端的连接

            // 创建线程执行任务
            thread t(std::bind(&tcp_server::thread_run, this, placeholders::_1), socket);
            t.detach(); // 线程分离
            // t.join();
        }
    }

    ~tcp_server()
    {
        delete _sv;
    }

private:
    my_socket *_sv;
    uint16_t _port;
    func_t _func;
};